package com.unionfetch.content_home.ui.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.unionfetch.content_home.R
import com.unionftech.common.R.dimen
import com.unionftech.common.R.style
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.Utils

class CustomSelectDialog(context: Context) : BottomSheetDialog(context) {
    private val mContext = context
    private lateinit var mContentView: View
    private val mLlDialogContent by lazy { mContentView.findViewById<LinearLayout>(R.id.ll_dialog_content) }
    private val mLlCustomItemContainer by lazy { mContentView.findViewById<LinearLayout>(R.id.ll_custom_item_container) }
    private val mDialogTitle by lazy { mContentView.findViewById<TextView>(R.id.tv_dialog_title) }
    private val mCacheView = mutableListOf<View>()
    private var mTitleText: String = ""
    private var mDataList = mutableListOf<String>()
    private var mSelectIndex = -1
    private var mCallBack: ((position: Int) -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContentView =
            LayoutInflater.from(mContext).inflate(R.layout.layout_custom_select_dialog, null)
        setView()
        setContentView(mContentView)
        setCancelable(true)
        setCanceledOnTouchOutside(true)
    }

    private fun setView() {
        setTitleText()
        obtainItemView()
        setViewData()
    }

    private fun setTitleText() {
        mDialogTitle.text = mTitleText
    }

    private fun obtainItemView() {
        while (mLlCustomItemContainer.childCount > mDataList.size) {
            val view = mLlCustomItemContainer.getChildAt(0)
            mLlCustomItemContainer.removeView(view)
            if (view != null) {
                mCacheView.add(view)
            }
        }
        while (mLlCustomItemContainer.childCount < mDataList.size) {
            var view: View? = mCacheView.getOrNull(0)
            if (view == null) {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.layout_wv_custom_dialog_item, null)
                view!!.tag = CustomItemViewHolder(view)
            } else {
                mCacheView.remove(view)
            }
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
            )
            layoutParams.topMargin =
                mContext.resources.getDimension(dimen.dp_16).toInt()
            mLlCustomItemContainer.addView(view, layoutParams)
        }
    }

    private fun setViewData() {
        mDataList.forEachIndexed { index, data ->
            mLlCustomItemContainer.getChildAt(index)?.also { view ->
                val viewHolder = setItemSelectBg(view, index)
                viewHolder.mTvItemText.text = data
                view.setOnClickListener {
                    if (!Utils.isFastDoubleClick(it.id)) {
                        removeSelect(mSelectIndex)
                        mSelectIndex = index
                        selectItem(mSelectIndex)
                        mCallBack?.invoke(index)
                        mLlCustomItemContainer.postDelayed({
                            dismiss()
                        }, 100)
                    }
                }
            }
        }
    }

    private fun selectItem(index: Int) {
        val view = mLlCustomItemContainer.getChildAt(index)
        if (view != null) {
            val viewHolder = view.tag as CustomItemViewHolder
            viewHolder.mIvItemSelect.visibility = View.VISIBLE
            viewHolder.mTvItemText.isSelected = true
            viewHolder.mItemContainer.setBackgroundResource(R.drawable.shape_account_select_bg)
        }
    }

    private fun removeSelect(index: Int) {
        val view = mLlCustomItemContainer.getChildAt(index)
        if (view != null) {
            val viewHolder = view.tag as CustomItemViewHolder
            viewHolder.mIvItemSelect.visibility = View.GONE
            viewHolder.mTvItemText.isSelected = false
            viewHolder.mItemContainer.background = null
        }
    }

    private fun setItemSelectBg(view: View, index: Int): CustomItemViewHolder {
        val viewHolder = view.tag as CustomItemViewHolder
        if (mSelectIndex == index) {
            selectItem(index)
        } else {
            removeSelect(index)
        }
        return viewHolder
    }

    fun setTitle(title: String): CustomSelectDialog {
        mTitleText = title
        return this
    }

    fun setItemData(list: List<String>): CustomSelectDialog {
        mDataList.clear()
        mDataList.addAll(list)
        return this
    }

    fun setSelectIndex(index: Int): CustomSelectDialog {
        mSelectIndex = index
        return this
    }

    fun setCallBack(callBack: (position: Int) -> Unit): CustomSelectDialog {
        mCallBack = callBack
        return this
    }

    override fun onStart() {
        super.onStart()
        window?.decorView?.setPadding(0, 0, 0, 0)
        window?.attributes?.gravity = Gravity.BOTTOM
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        window?.attributes?.windowAnimations = style.BottomDialogAnimation
        val behavior = BottomSheetBehavior.from(mLlDialogContent)
        behavior.peekHeight = getWindowHeight()
        behavior.state = BottomSheetBehavior.STATE_EXPANDED
        window?.also {
            Utils.setDialogNavigationBarTransparent(it)
        }
        setView()
    }

    /**
     * 计算高度(初始化可以设置默认高度)
     *
     * @return
     */
    private fun getWindowHeight(): Int {
        mLlCustomItemContainer.measure(0, 0)
        val dp44 = mContext.resources.getDimension(dimen.dp_44)
        val height = mLlCustomItemContainer.measuredHeight + dp44.toInt()
        LogUtils.d(CustomSelectDialog::class.java.simpleName, "getWindowHeight--->${height}")
        return height
    }

    class CustomItemViewHolder(view: View) {
        private val itemView = view
        internal val mItemContainer: FrameLayout by lazy { itemView.findViewById(R.id.item_container) }
        internal val mIvItemSelect: ImageView by lazy { itemView.findViewById(R.id.iv_item_select) }
        internal val mTvItemText: TextView by lazy { itemView.findViewById(R.id.tv_item_text) }
    }
}